import { LitElement, html, css } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import * as echarts from 'echarts';
import chinaMap from './assets/china.json';

@customElement('map-annotator')
export default class MapAnnotator extends LitElement {
  @state() private chart: echarts.ECharts | null = null;
  @state() private selectedProvince: string | null = null;
  @state() private annotations: Array<{ province: string, note: string }> = [];
  @state() private newNote: string = '';
  @state() private provinceMarks: Record<string, number> = {};
  @state() private markProvince: string = '';
  @state() private markCount: string = '1';
  @state() private darkMode: boolean = false;

  firstUpdated() {
    this.initChart();
  }

  private initChart() {
    //@ts-ignore
    echarts.registerMap("china", { geoJSON: chinaMap });

    const chartDom = this.shadowRoot?.getElementById('map') as HTMLElement;
    this.chart = echarts.init(chartDom);

    this.updateChart();

    // 保留点击事件用于可能的扩展
    this.chart.on('click', () => { });
  }

  private updateChart() {
    if (!this.chart) return;

    // 强制清除之前的选择状态
    this.chart.dispatchAction({
      type: 'unselect',
      seriesIndex: 0
    });

    const baseColor = this.darkMode ? 'hsla(210, 30%, 70%, 0.7)' : 'hsla(195, 50%, 85%, 0.7)';
    const borderColor = this.darkMode ? 'hsla(210, 20%, 50%, 0.5)' : 'hsla(195, 30%, 70%, 0.5)';

    const annotationData = this.annotations.map(anno => ({
      name: anno.province,
      itemStyle: {
        areaColor: baseColor,
        borderColor: borderColor,
        borderWidth: 0.8,
        opacity: 0.7,
        shadowColor: 'rgba(0, 0, 0, 0.1)',
        shadowBlur: 5
      },
      emphasis: {
        itemStyle: {
          areaColor: baseColor,
          opacity: 1
        }
      }
    }));

    const markData = Object.entries(this.provinceMarks).map(([province, count]) => ({
      name: province,
      itemStyle: {
        areaColor: this.getColorByCount(count),
        borderColor: this.darkMode ? 'hsla(0, 0%, 40%, 0.3)' : 'hsla(0, 0%, 60%, 0.3)',
        borderWidth: 0.8,
        opacity: 0.9,
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 5,
        shadowOffsetX: 2,
        shadowOffsetY: 2,
        emphasis: {
          shadowBlur: 15,
          shadowOffsetX: 5,
          shadowOffsetY: 5
        }
      },
      emphasis: {
        itemStyle: {
          areaColor: this.getColorByCount(count),
          opacity: 1
        }
      },
      label: {
        show: true,
        formatter: count > 1 ? `{b}\n${count}` : '{b}',
        color: this.darkMode ? '#fff' : '#333'
      }
    }));

    const data = [...annotationData, ...markData];
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          const annotation = this.annotations.find(a => a.province === params.name);
          return `${params.name}${annotation ? '<br/>' + annotation.note : ''}`;
        }
      },
      // backgroundColor: this.darkMode ? '#222' : '#fff',
      visualMap: {
        show: false,
        min: Object.values(this.provinceMarks).reduce((a, b) => Math.min(a, b), Infinity) - 10,
        max: Object.values(this.provinceMarks).reduce((a, b) => Math.max(a, b), -Infinity),
        inRange: {
          color: [
            '#313695',
            '#4575b4',
            '#74add1',
            '#abd9e9',
            '#e0f3f8',
            '#ffffbf',
            '#fee090',
            '#fdae61',
            '#f46d43',
            '#d73027',
            '#a50026'
          ]
        },
      },
      series: [{
        name: '中国地图',
        type: 'map',
        map: 'china',
        roam: true,
        itemStyle: {
          areaColor: this.darkMode ? '#333' : '#f5f5f5',
          borderColor: this.darkMode ? '#444' : '#ddd',
          borderWidth: 1,
          emphasis: {
            areaColor: this.darkMode ? '#555' : '#eee'
          }
        },
        light: {
          main: {
            intensity: 1.2,
            shadow: true,
            shadowQuality: 'high',
            alpha: 30,
            beta: 40
          },
          ambient: {
            intensity: 0.3
          }
        },
        emphasis: {
          label: {
            show: true,
            color: this.darkMode ? '#fff' : '#333'
          },
          itemStyle: {
            areaColor: this.darkMode ? '#666' : '#ddd'
          }
        },
        data: data.map(item => ({
          ...item,
          visualMap: 5 // 基础高度
        }))
      }]
    };

    // 强制更新图表
    this.chart.setOption(option, true);
  }

  private addAnnotation() {
    if (!this.selectedProvince || !this.newNote) return;

    this.annotations = [
      ...this.annotations.filter(a => a.province !== this.selectedProvince),
      {
        province: this.selectedProvince!,
        note: this.newNote
      }
    ];

    this.newNote = '';
    this.updateChart();
  }

  private removeAnnotation(province: string) {
    this.annotations = this.annotations.filter(a => a.province !== province);
    this.updateChart();
  }
  /**
   * 标注省份
   * @param province 省份名称
   * @param count 可选，标注数量，用于颜色渐变
   */
  public addProvinceMark(province: string, count?: number) {
    // 创建新对象确保状态更新被检测到
    this.provinceMarks = {
      ...this.provinceMarks,
      [province]: count || 1
    };
    this.updateChart();
  }
  private getColorByCount(count: number): string {
    // 柔和自然配色方案 - 从浅蓝到浅粉渐变
    const maxCount = Math.max(...Object.values(this.provinceMarks), 1);
    const ratio = count / maxCount;

    // 基础色调
    const hue = 200 + 120 * ratio; // 200°(浅蓝)到320°(浅粉)
    const saturation = 40; // 降低饱和度
    const lightness = this.darkMode ? 70 : 80; // 提高亮度

    return `hsla(${hue}, ${saturation}%, ${lightness}%, 0.6)`;
  }

  private handleAddMark() {
    if (!this.markProvince) return;
    const count = parseInt(this.markCount) || 1;
    this.addProvinceMark(this.markProvince, count);
    this.markProvince = '';
    this.markCount = '1';
  }
  private toggleTheme = () => {
    this.darkMode = !this.darkMode;
    this.updateChart();
  };

  private async exportImage() {
    if (!this.chart) return;

    const dataURL = this.chart.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    });

    // 创建下载链接
    const link = document.createElement('a');
    link.href = dataURL;
    link.download = '中国地图标注.png';
    link.click();
  }

  static styles = css`
    :host {
      display: block;
      width: 100%;
      height: 100%;
    }

    :host {
      display: flex;
      height: 100%;
    }

    .map-container {
      flex: 1;
      height: 100%;
      min-height: 600px;
      width: 800px;
      position: relative;
    }
    
    #map {
      width: 100%;
      height: 100%;
    }

    .control-panel {
      width: 300px;
      background: var(--panel-bg, white);
      color: var(--text-color, #333);
      padding: 15px;
      border-left: 1px solid var(--border-color, #eee);
      display: flex;
      flex-direction: column;
      overflow-y: auto;
    }

    textarea {
      width: 100%;
      margin: 5px 0;
      padding: 5px;
      box-sizing: border-box;
    }

    button {
      margin: 5px 0;
      padding: 5px 10px;
      cursor: pointer;
      width: 100%;
    }

    .annotations-list {
      margin-top: 10px;
      border-top: 1px solid #eee;
      padding-top: 10px;
    }

    .annotation-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 5px 0;
      padding: 5px;
      background: var(--item-bg, #f5f5f5);
      color: var(--text-color, #333);
      border-radius: 3px;
    }

    .annotation-item button {
      width: auto;
      padding: 2px 5px;
      margin-left: 5px;
    }

    .section {
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }

    .section h4 {
      margin: 0 0 8px 0;
      color: #666;
    }

    input[type="text"],
    input[type="number"] {
      width: 100%;
      margin: 5px 0;
      padding: 5px;
      box-sizing: border-box;
    }
  `;

  // 后续将实现具体功能
  render() {
    return html`
      <div class="map-container" id="map"></div>
      <div class="control-panel" part="control-panel">
        <div class="section">
          <h4>手动标注</h4>
          <input
            type="text"
            .value=${this.markProvince}
            @input=${(e: Event) => this.markProvince = (e.target as HTMLInputElement).value}
            placeholder="输入省份名称"
          />
          <input
            type="number"
            .value=${this.markCount}
            @input=${(e: Event) => this.markCount = (e.target as HTMLInputElement).value}
            placeholder="数量(可选)"
            min="1"
          />
          <button @click=${this.handleAddMark}>添加数量标注</button>
        </div>

        ${this.selectedProvince
        ? html`
            <div class="section">
              <h4>交互标注</h4>
              <div>已选择: ${this.selectedProvince}</div>
              <textarea 
                .value=${this.newNote}
                @input=${(e: Event) => this.newNote = (e.target as HTMLTextAreaElement).value}
                placeholder="输入标注内容"
                rows="3"
              ></textarea>
              <button @click=${this.addAnnotation}>添加文字标注</button>
            </div>
          `
        : html`<div>请点击地图选择省份</div>`}
        
        ${this.annotations.length > 0 ? html`
          <div class="annotations-list">
            <h4>已有标注:</h4>
            ${this.annotations.map(anno => html`
              <div class="annotation-item">
                <span>${anno.province}: ${anno.note}</span>
                <button @click=${() => this.removeAnnotation(anno.province)}>删除</button>
              </div>
            `)}
          </div>
        ` : ''}
        
        <button @click=${this.toggleTheme}>切换${this.darkMode ? '浅色' : '深色'}主题</button>
        <button @click=${this.exportImage}>导出图片</button>
      </div>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'cpzxrobot-map-annotator': MapAnnotator;
  }
}